package com.starbugs.wehcat.controller;

import com.starbugs.wehcat.data.OrderRepository;
import com.starbugs.wehcat.pojo.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import javax.validation.Valid;

/**
 * @author starbooks
 */
@Slf4j
@Controller
@RequestMapping("/orders")
@SessionAttributes("order")
public class OrdersController {

  private OrderRepository orderRepo;

  public OrdersController(OrderRepository orderRepo) {
    this.orderRepo = orderRepo;
  }

  @GetMapping("/current")
  public String orderForm(Model model){
    return "orderForm";
  }

  @PostMapping
  public String processOrder(@Valid Order order, Errors errors, SessionStatus sessionStatus){
    if(errors.hasErrors()){
      return "orderForm";
    }
    this.orderRepo.save(order);
    // 如果我们不把它清理掉，那么订单会继续保留在session中
    sessionStatus.setComplete();
    log.info("Order submitted: " + order);
    return "redirect:/";
  }

}
